package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.model.business.vo.cache.result.TagName;
import com.ndp.fb.rdb.api.TagForBuildnameRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.TagForBuildnameSeq;

import java.util.List;

/**
 * Created by evan.wan on 2015/6/15.
 */
@Service
public class TagForBuildnameRdbServiceImpl  extends DaoTemplate implements TagForBuildnameRdbService {


    @Override
    public List<TagName> getTag()
    {
        String sql = "SELECT * FROM t_tag_for_buildname ORDER BY id";
        return getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(TagName.class));
    }

    @Override
    public List<TagName> getTagEN()
    {
        String sql = "SELECT t.en_tag_name AS tag_name, t.* FROM t_tag_for_buildname t ORDER BY id";
        return getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(TagName.class));
    }

    @Override
    public TagForBuildnameSeq getSeq(String userId, Long fbConnObjId, Long productCfgId)
    {
        String sql = "SELECT * FROM t_tag_for_buildname_seq WHERE 1=1 AND user_id = ? AND fb_conn_obj_id = ? AND product_cfg_id = ? ";
        List<TagForBuildnameSeq> list =  getJdbcTemplate().query(sql, new Object[]{userId, fbConnObjId, productCfgId}, DefaultRowMapper.autoRowMapper(TagForBuildnameSeq.class));
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void saveSeq(TagForBuildnameSeq seq) {
        //同一个用户,这里互斥的
    	synchronized (seq.getUserId()) {
    		//当这里获取数据库超时的时候会锁住
            if(getSeq(seq.getUserId(), seq.getFbConnObjId(), seq.getProductCfgId()) != null) {
                String sql = "UPDATE t_tag_for_buildname_seq SET ad_camp_seq = ?,ad_set_seq = ?, ad_group_seq = ? WHERE 1=1 AND user_id = ? AND fb_conn_obj_id = ? AND product_cfg_id = ? ";
                Object[] param  = new Object[]{seq.getAdCampSeq(), seq.getAdSetSeq(), seq.getAdGroupSeq(), seq.getUserId(), seq.getFbConnObjId(), seq.getProductCfgId()};
                getJdbcTemplate().update(sql, param);
            }
            else {
                saveResultId(seq);
            }
    	}
    	
    }

}
